<template>
  <section class="profile-page">
    <el-row :gutter="16">
      <el-col :xs="24" :sm="24" :md="8" :lg="7">
        <el-card shadow="always" class="profile-card">
          <div class="profile-header">
            <el-avatar :size="72" :src="user.avatar" />
            <div class="profile-header__meta">
              <div class="name">
                {{ user.name }}
                <el-tag size="small" type="info" class="id-tag">ID: {{ user.id }}</el-tag>
              </div>
              <div class="sub">欢迎回来，以下为您的账户概览</div>
            </div>
          </div>

          <el-divider content-position="left">头像管理</el-divider>
          <div class="avatar-upload">
            <el-upload
              class="upload"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="handleAvatarChange"
            >
              <el-button type="primary" plain>更换头像（模拟）</el-button>
            </el-upload>
            <div class="tip text-muted">仅演示更新预览，不会上传到后端</div>
          </div>

          <el-divider content-position="left">概览</el-divider>
          <el-descriptions :column="1" size="small" border>
            <el-descriptions-item label="邮箱">{{ user.email }}</el-descriptions-item>
            <el-descriptions-item label="手机号">{{ user.phone }}</el-descriptions-item>
          </el-descriptions>

          <el-divider content-position="left">资料完善度</el-divider>
          <div class="progress-block">
            <div class="progress-line">
              <span class="label">完善度</span>
              <el-popover placement="top" width="200" trigger="hover">
                <template #default>
                  完善姓名、邮箱、手机号与头像即可提高资料完成度。
                </template>
                <template #reference>
                  <el-icon class="help-icon"><question-filled /></el-icon>
                </template>
              </el-popover>
            </div>
            <el-progress :percentage="profileCompletion" :status="profileCompletion >= 80 ? 'success' : 'warning'" />
          </div>

          <el-divider content-position="left">小统计</el-divider>
          <div class="stat-grid">
            <el-card shadow="hover" class="stat-item">
              <div class="stat-title">今日登录</div>
              <div class="stat-value">2 次</div>
            </el-card>
            <el-card shadow="hover" class="stat-item">
              <div class="stat-title">消息通知</div>
              <div class="stat-value">5 条</div>
            </el-card>
          </div>

          <el-divider content-position="left">成就徽章</el-divider>
          <div class="badge-grid">
            <el-tag v-for="b in achievements" :key="b.key" :type="b.type" effect="light" class="badge-item">
              <el-badge :value="b.level" :max="9" type="primary">{{ b.name }}</el-badge>
            </el-tag>
            <el-empty v-if="!achievements.length" description="暂无成就" />
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="24" :md="16" :lg="17">
        <el-card shadow="always" class="edit-card">
          <template #header>
            <div class="card-header">
              <span>个人中心</span>
              <div class="actions">
                <el-button type="default" @click="reload" :loading="loading">重新加载</el-button>
              </div>
            </div>
          </template>

          <el-tabs v-model="activeTab" class="tabs">
            <el-tab-pane label="资料编辑" name="edit">
              <div v-if="loading" class="loading-block">
                <el-skeleton :rows="4" animated />
                <div class="text-muted mt-8">正在加载用户信息...</div>
              </div>

              <div v-else>
                <el-form
                  ref="formRef"
                  :model="user"
                  :rules="rules"
                  label-width="88px"
                  status-icon
                  class="profile-form"
                >
                  <el-form-item label="邮箱" prop="email">
                    <el-input v-model="user.email" placeholder="请输入邮箱" clearable />
                  </el-form-item>
                  <el-form-item label="手机号" prop="phone">
                    <el-input v-model="user.phone" placeholder="请输入手机号" clearable />
                  </el-form-item>

                  <el-form-item>
                    <el-button type="primary" @click="onSubmit" :loading="saving">
                      {{ saving ? "保存中..." : "保存资料" }}
                    </el-button>
                    <el-button @click="resetForm">重置更改</el-button>
                  </el-form-item>

                  <el-alert
                    v-if="message"
                    :title="message"
                    type="success"
                    show-icon
                    class="mt-8"
                  />
                </el-form>

                <el-divider>最近活动</el-divider>
                <el-timeline>
                  <el-timeline-item timestamp="2025-09-28" type="primary">
                    更换了头像
                  </el-timeline-item>
                  <el-timeline-item timestamp="2025-09-27" type="success">
                    更新了联系方式
                  </el-timeline-item>
                  <el-timeline-item timestamp="2025-09-25" type="warning">
                    开启了消息通知
                  </el-timeline-item>
                </el-timeline>
              </div>
            </el-tab-pane>

            <el-tab-pane label="偏好设置" name="preferences">
              <el-form :model="preferences" label-width="120px" class="pref-form">
                <el-form-item label="消息通知">
                  <el-switch v-model="preferences.enableNotifications" active-text="开启" inactive-text="关闭" />
                </el-form-item>
                <el-form-item label="主题风格">
                  <el-select v-model="preferences.theme" placeholder="选择主题" style="width: 220px">
                    <el-option label="浅色" value="light" />
                    <el-option label="深色" value="dark" />
                    <el-option label="系统" value="system" />
                  </el-select>
                </el-form-item>
                <el-form-item label="界面语言">
                  <el-select v-model="preferences.language" placeholder="选择语言" style="width: 220px">
                    <el-option label="中文" value="zh-CN" />
                    <el-option label="English" value="en-US" />
                    <el-option label="日本語" value="ja-JP" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="savePreferences">保存偏好（模拟）</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>

            <el-tab-pane label="安全设置" name="security">
              <el-alert title="建议开启两步验证提升账号安全" type="info" show-icon class="mb-12" />
              <el-form :model="security" label-width="120px" class="security-form">
                <el-form-item label="两步验证">
                  <el-switch v-model="security.twoFA" active-text="已开启" inactive-text="未开启" />
                </el-form-item>

                <el-divider>修改密码</el-divider>
                <el-form
                  ref="pwdFormRef"
                  :model="pwdForm"
                  :rules="pwdRules"
                  label-width="120px"
                  status-icon
                >
                  <el-form-item label="当前密码" prop="current">
                    <el-input v-model="pwdForm.current" type="password" placeholder="请输入当前密码" show-password />
                  </el-form-item>
                  <el-form-item label="新密码" prop="next">
                    <el-input v-model="pwdForm.next" type="password" placeholder="请输入新密码" show-password />
                  </el-form-item>
                  <el-form-item label="确认新密码" prop="confirm">
                    <el-input v-model="pwdForm.confirm" type="password" placeholder="请再次输入新密码" show-password />
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="changePassword">提交（模拟）</el-button>
                  </el-form-item>
                </el-form>

                <el-divider>最近登录会话</el-divider>
                <el-table :data="sessions" style="width: 100%" size="small" stripe>
                  <el-table-column prop="time" label="时间" width="160" />
                  <el-table-column prop="device" label="设备" />
                  <el-table-column prop="location" label="位置" />
                  <el-table-column prop="ip" label="IP" width="140" />
                  <el-table-column label="状态" width="120">
                    <template #default="scope">
                      <el-tag :type="scope.row.status === '成功' ? 'success' : 'warning'">{{ scope.row.status }}</el-tag>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
  </section>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, computed } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { QuestionFilled } from "@element-plus/icons-vue";

interface UserInfo {
  id: string;
  name: string;
  email: string;
  phone: string;
  avatar: string;
}

interface PreferenceInfo {
  enableNotifications: boolean;
  theme: "light" | "dark" | "system";
  language: "zh-CN" | "en-US" | "ja-JP";
}

interface SecurityInfo {
  twoFA: boolean;
}

interface SessionRow {
  time: string;
  device: string;
  location: string;
  ip: string;
  status: "成功" | "异常";
}

interface BadgeInfo {
  key: string;
  name: string;
  type: "success" | "warning" | "info" | "danger";
  level: number;
}

const user = reactive<UserInfo>({
  id: "",
  name: "",
  email: "",
  phone: "",
  avatar: "https://via.placeholder.com/72",
});

const preferences = reactive<PreferenceInfo>({
  enableNotifications: true,
  theme: "system",
  language: "zh-CN",
});

const security = reactive<SecurityInfo>({
  twoFA: false,
});

const sessions = ref<SessionRow[]>([
  { time: "2025-09-29 10:21", device: "Windows 11", location: "Shanghai", ip: "10.0.0.12", status: "成功" },
  { time: "2025-09-28 20:05", device: "iPhone 15", location: "Shanghai", ip: "10.0.0.22", status: "成功" },
  { time: "2025-09-27 08:17", device: "MacBook Pro", location: "Hangzhou", ip: "10.0.0.33", status: "异常" },
]);

const achievements = ref<BadgeInfo[]>([
  { key: "starter", name: "新手上路", type: "info", level: 1 },
  { key: "profile", name: "完善资料", type: "success", level: 2 },
  { key: "secure", name: "安全达人", type: "warning", level: 1 },
]);

const loading = ref(false);
const saving = ref(false);
const message = ref("");
const activeTab = ref<"edit" | "preferences" | "security">("edit");

const formRef = ref<FormInstance>();
const pwdFormRef = ref<FormInstance>();

// 模拟接口：获取与保存用户信息
function mockFetchUser(): Promise<UserInfo> {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        id: "u_10001",
        name: "张三",
        email: "zhangsan@example.com",
        phone: "13800001111",
        avatar: "https://picsum.photos/seed/user/72/72",
      });
    }, 600);
  });
}

function mockSaveUser(u: UserInfo): Promise<void> {
  return new Promise((resolve) => setTimeout(() => resolve(), 800));
}

function mockSavePreferences(p: PreferenceInfo): Promise<void> {
  return new Promise((resolve) => setTimeout(() => resolve(), 500));
}

function mockChangePassword(_: { current: string; next: string }): Promise<void> {
  return new Promise((resolve) => setTimeout(() => resolve(), 700));
}

// 表单校验规则
const rules: FormRules = {
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "邮箱格式不正确", trigger: ["blur", "change"] },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      validator: (_rule, value, callback) => {
        const ok = /^1[3-9]\d{9}$/.test(String(value || ""));
        ok ? callback() : callback(new Error("手机号格式不正确"));
      },
      trigger: ["blur", "change"],
    },
  ],
};

// 修改密码表单与规则
const pwdForm = reactive({ current: "", next: "", confirm: "" });
const pwdRules: FormRules = {
  current: [{ required: true, message: "请输入当前密码", trigger: "blur" }],
  next: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, message: "至少6位字符", trigger: "blur" },
  ],
  confirm: [
    { required: true, message: "请再次输入新密码", trigger: "blur" },
    {
      validator: (_r, v, cb) => {
        v === pwdForm.next ? cb() : cb(new Error("两次输入不一致"));
      },
      trigger: ["blur", "change"],
    },
  ],
};

const profileCompletion = computed(() => {
  let score = 0;
  if (user.name) score += 20;
  if (user.email) score += 20;
  if (user.phone) score += 20;
  if (user.avatar) score += 20;
  if (security.twoFA) score += 20;
  return Math.min(100, score);
});

async function load() {
  loading.value = true;
  message.value = "";
  const data = await mockFetchUser();
  Object.assign(user, data);
  loading.value = false;
}

async function onSubmit() {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (!valid) return;
    saving.value = true;
    message.value = "";
    await mockSaveUser(user);
    saving.value = false;
    message.value = "资料已保存（模拟后端）。";
    ElMessage.success("保存成功");
  });
}

function resetForm() {
  formRef.value?.resetFields();
}

function reload() {
  load();
}

function handleAvatarChange(file: any) {
  // 模拟：本地预览替换头像
  const reader = new FileReader();
  reader.onload = () => {
    user.avatar = String(reader.result || user.avatar);
    ElMessage.success("头像更新预览成功（未上传）");
  };
  reader.readAsDataURL(file.raw);
}

async function savePreferences() {
  await mockSavePreferences(preferences);
  ElMessage.success("偏好设置已保存（模拟）");
}

async function changePassword() {
  if (!pwdFormRef.value) return;
  await pwdFormRef.value.validate(async (valid) => {
    if (!valid) return;
    await mockChangePassword({ current: pwdForm.current, next: pwdForm.next });
    ElMessage.success("密码已修改（模拟）");
    pwdForm.current = "";
    pwdForm.next = "";
    pwdForm.confirm = "";
  });
}

onMounted(load);
</script>

<style scoped lang="scss">
.profile-page {
  padding: 16px;
}
.profile-card {
  .profile-header {
    display: flex;
    align-items: center;
    gap: 12px;
    &__meta {
      display: flex;
      flex-direction: column;
      .name {
        font-size: 18px;
        font-weight: 600;
        display: flex;
        align-items: center;
        gap: 8px;
      }
      .sub {
        font-size: 13px;
        color: var(--el-text-color-secondary);
      }
    }
  }
  .id-tag {
    vertical-align: middle;
  }
  .avatar-upload {
    display: flex;
    align-items: center;
    gap: 12px;
    .tip {
      font-size: 12px;
      color: var(--el-text-color-secondary);
    }
  }
  .progress-block {
    .progress-line {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 6px;
      .label {
        font-size: 13px;
        color: var(--el-text-color-secondary);
      }
      .help-icon {
        color: var(--el-color-primary);
        cursor: help;
      }
    }
  }
  .stat-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 12px;
    .stat-item {
      .stat-title {
        font-size: 13px;
        color: var(--el-text-color-secondary);
      }
      .stat-value {
        font-size: 20px;
        font-weight: 600;
        margin-top: 6px;
      }
    }
  }
  .badge-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    .badge-item {
      padding: 6px 8px;
    }
  }
}
.edit-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .tabs {
    margin-top: 8px;
  }
  .profile-form {
    max-width: 560px;
  }
  .pref-form,
  .security-form {
    max-width: 640px;
  }
  .loading-block {
    padding: 8px 0;
  }
}
.mt-8 {
  margin-top: 8px;
}
.mb-12 {
  margin-bottom: 12px;
}
.text-muted {
  color: var(--el-text-color-secondary);
}
</style>